<template>
  <div class="main-header-box">
    <header class="main-header">
      <div class="container">
        <router-link class="logo-inner" to="/">
          <span class="logo-text"></span>
        </router-link>
        <nav role="navigation" class="main-nav clearfix">
          <ul class="nav-list">
            <li class="main-nav-list clearfix">
              <ul
                v-for="item in mainNavList"
                :key="item.path"
                class="main-nav-list-container">
                <li class="nav-item link-item">
                  <router-link
                    :class="{'link-active': item.path.indexOf(calNavPath) === 0 }"
                    :to="item.path">{{item.name}}</router-link>
                </li>
              </ul>
            </li>
            <li class="search">
              <ul class="main-nav-list-container search-container">
                <search ref="search"></search>
              </ul>
            </li>
            <li class="document">
              <img class="icon-document" src="@/common/image/icon/document.png">
              <span @click="toDocument">帮助</span>
            </li>
            <li class="avatar" v-if="hiddenPortraits">
              <el-popover
                placement="bottom-end"
                width="500"
                trigger="hover"
                popper-class="headermovepopper"
                v-model="popoverVisible">
                <div class="header-popover">
                  <div class="pop-header">
                    <div class="pop-header-left">
                      <div>
                        <p><span>{{userInfo.username ? userInfo.username : '-'}}</span> @{{userInfo.account ? userInfo.account : '-'}}</p>
                      </div>
                    </div>
                    <div class="pop-header-right">
                      <button class="invite" @click="copyCode">邀请新用户</button>
                      <button @click="toModifyInfo">修改资料</button>
                    </div>
                  </div>
                  <div class="pop-team">
                    <ul class="pop-team-wrap">
                      <li class="pop-team-ico">
                          <img src="@/common/image/team-all-ico.png" alt="">
                      </li>
                      <li class="pop-team-item" v-for="(item, index) in teamDataSet" :key="index" @click="goTeamHomeFun(item.teamId,item.role)">{{item.teamName}}</li>
                      <li class="pop-team-add" v-if="!hiddenCreate" @click="createTeamFun">
                        + 创建团队
                      </li>
                    </ul>
                  </div>
                  <div class="line"></div>
                  <div class="pop-order">
                    <div class="pop-calc">
                      <div class="pop-calc-left">
                        <img class="order-icon" src="@/common/image/icon/icon-suanli.png" />
                        <p>可用算力：<span class="num-lan">{{powerSur}}</span></p>
                      </div>
                      <div class="pop-calc-right">
                        <button @click="routeTo('/order')">算力充值</button>
                      </div>
                    </div>
                    <div class="pop-storage">
                      <img class="order-icon" src="@/common/image/icon/icon-cuncu.png" />
                      <p>可用存储：<span class="num-lan">{{storageTotal - storageUsed}}GB</span> <span>共{{storageTotal}}GB</span></p>
                    </div>
                  </div>
                  <div class="line"></div>
                  <div class="pop-nav">
                    <div class="pop-nav-item nav-user" @click="routeTo('/index')">
                      <p>个人中心</p>
                    </div>
                    <div class="pop-nav-item nav-price" @click="routeTo('/personalmirror')">
                      <p>我的镜像</p>
                    </div>
                    <div class="pop-nav-item nav-price" @click="toCostCenter">
                      <p>费用中心</p>
                    </div>
                    <div class="pop-nav-item nav-calc" @click="routeTo('/order/list')">
                      <p>算力明细</p>
                    </div>
                  </div>
                  <div class="line"></div>
                  <div class="pop-footer">
                    <span @click="_logOut">退出当前账户</span>
                  </div>
                </div>
                <img
                  slot="reference"
                  class="avatar-item"
                  :src="userInfo.headImage"
                  alt="avatar" />
              </el-popover>
            </li>
          </ul>
        </nav>
      </div>
    </header>
  </div>
</template>

<script>
import Search from '../search/search'
import { getUserCalculationPower, queryStorage, getOrderStorageCountByUserId } from '@/api/order'
import { getTeamList } from '@/api/team_list'
import { mapMutations, mapGetters } from 'vuex'
import { logOut } from '@/api/user'
import qs from 'qs'

export default {
  inject: ['reload'],
  data () {
    return {
      // 可用算力
      powerSur: 0,
      // 已用存储
      storageUsed: 0,
      // 总存储
      storageTotal: 0,
      teamDataSet: [],
      hiddenCreate: false,
      hiddenPortraits: true,
      mainNavList: [
        {
          path: '/project/list',
          name: '项目'
        },
        // {
        //   path: '/filecenter',
        //   name: '文件'
        // },
        {
          path: '/dataset',
          name: '数据集'
        },
        {
          path: '/modellump',
          name: '模型'
        },
        {
          path: '/openproject',
          name: '公开项目'
        }
      ],
      popoverVisible: false
    }
  },
  computed: {
    calNavPath: function () {
      let path = this.$route.path.split('/')
      return `/${path[1]}`
    },
    ...mapGetters([
      'userInfo'
    ])
  },
  mounted () {
    if (this.$route.path === '/jointeam') {
      if (this.userInfo && this.userInfo.token) {
        this.hiddenPortraits = true
      } else {
        this.hiddenPortraits = false
      }
    } else {
      if (this.userInfo && this.userInfo.token) {
        this.hiddenPortraits = true
        this.queryData()
      }
    }
  },
  methods: {
    // 路由调转
    routeTo (path) {
      this.popoverVisible = false
      this.$router.push({ 'path': path })
    },
    goTeamHomeFun (teamid, role) {
      if (this.$route.path === '/team/detail/member' || this.$route.path === '/team/detail/count') {
        this.$router.push({ path: '/team/detail/member', query: { id: teamid, role: role } })
        this.reload()
      } else {
        this.$router.push({ path: '/team/detail/member', query: { id: teamid, role: role } })
        this.reload()
      }
    },
    createTeamFun () {
      this.popoverVisible = false
      this.$router.push({ path: '/teamadd' })
    },
    // 打开新页面
    toModifyInfo () {
      this.popoverVisible = false
      window.open(`${process.env.VUE_APP_BITA_EDIT_INFO}?token=${this.userInfo.bitaToken}`)
    },
    toDocument () {
      window.open(`${process.env.VUE_APP_HELP}/help/index.html`)
    },
    // 打开费用中心
    toCostCenter () {
      this.popoverVisible = false
      window.open(`${process.env.VUE_APP_BITA_COST_CENTER}?token=${this.userInfo.bitaToken}`)
    },
    queryData () {
      this._getAvailablePower()
      this._getStorageInfo()
      this._getTeamList()
      this._getOrderStorageCountByUserId()
    },
    // 邀请用户
    copyCode () {
      const str = `Hi，我邀请你加入BitaHub，通过${process.env.VUE_APP_BITA_REGISTER + '?inviteid=' + this.userInfo.id}完成注册`
      this.copyToClipboard(str)
    },
    copyToClipboard (s) {
      const createInput = document.createElement('input')
      createInput.value = s
      document.body.appendChild(createInput)
      createInput.select()
      document.execCommand('Copy')
      createInput.style.display = 'none'
      this.$message({
        message: '邀请内容已复制到剪贴板',
        type: 'success'
      })
    },
    /*
      -----接口调用-----
    */
    // 退出
    _logOut () {
      logOut().then(res => {
        if (res.message.code === 0) {
          this.setLogOut()
          this.$router.push({ 'path': '/' })
        } else {
          this.setLogOut()
          this.$router.push({ 'path': '/' })
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 查询可用算力
    _getAvailablePower () {
      const query = `?token=${this.userInfo.bitaToken}`
      getUserCalculationPower(query).then(res => {
        if (res.code === 0) {
          this.powerSur = res.result.surplusCalculationPower.toFixed(1)
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查询全部团队名称
    _getTeamList () {
      getTeamList().then(res => {
        if (res.message.code === 0) {
          this.teamDataSet = res.data.teamList
          this.hiddenCreate = res.data.createTeam
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查看存储详情
    _getStorageInfo () {
      const query = `?token=${this.userInfo.bitaToken}`
      queryStorage(query).then(res => {
        if (res.code === 0) {
          this.storageUsed = res.result.storageSize.toFixed(1)
          this._getOrderStorageCountByUserId()
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 查询总存储空间
    _getOrderStorageCountByUserId () {
      const data = qs.stringify({
        token: this.userInfo.bitaToken
      })
      getOrderStorageCountByUserId(data).then(res => {
        if (res.code === 0) {
          this.storageTotal = res.result.toFixed(1)
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    ...mapMutations({
      setLogOut: 'LOG_OUT'
    })
  },
  components: {
    Search
  }
}
</script>

<style scoped lang="stylus">
@import '../../common/stylus/mixin'
@import '../../common/stylus/variable'

.main-header-box
  flex 0 0 auto
  position relative
  height 68px
  .main-header
    background #2196F3
    color #909399
    height 100%
    z-index 200
    box-sizing border-box
    .container
      display flex
      align-items center
      position relative
      max-width 1162px
      margin auto
      height 100%
      .logo-inner
        display inline-block
      .logo-text
        model(107px, 21px)
        display inline-block
        background-image url('../../common/image/bitahub-log-ico-hover.png')
        background-size 107px 21px
        &:hover
          background-image url('../../common/image/bitahub-log-ico.png')
          background-size 107px 21px
      .main-nav
        height 100%
        flex 1 0 auto
        .nav-list
          display flex
          align-items center
          height 100%
          margin 0
          justify-content space-between
          position relative
          .avatar
            .avatar-item
              width 25px
              height 25px
              border-radius 50%
              cursor pointer
          .search
            display flex
            flex 1 1 auto
            padding 0 20px
            justify-content flex-end
          .document
            padding 0 20px
            display flex
            align-items center
            .icon-document
              width 14px
              margin-right 6px
            >span
              font-size 14px
              color #B1DBFA
              cursor pointer
              &:hover
                color #ffffff
          .main-nav-list
            display flex
            height 100%
            padding-left 128px
            .main-nav-list-container
              display flex
              .nav-item
                font-size 14px
                display flex
                justify-content center
                align-items center
                cursor pointer
                position relative
                margin 0
                >a
                  text-decoration none
                  cursor pointer
                  color #B1DBFA
                  font-weight 600
                  font-size 14px
                  font-weight 600
                >a:before
                  content ''
                  position absolute
                  top 0
                  right 0
                  bottom 0
                  left 0
              .link-item
                height 100%
                margin-right 33px
            .link-active
              color #ffffff!important
.header-popover
  .pop-team
    padding 0 40px 25px
    .pop-team-wrap
      display flex
      flex-wrap wrap
      align-items center
      .pop-team-ico
        width 22px
        height 22px
        margin-right 7px
        img
          width 22px
          height 22px
      .pop-team-item
        font-size 14px
        color #6e6e6e
        line-height 20px
        margin-right 9px
        cursor pointer
      .pop-team-add
        font-size 14px
        line-height 20px
        color #2196F3
        padding-left 2px
        cursor pointer
  .pop-header
    padding 32px 17px 17px 40px
    display flex
    justify-content space-between
    align-items center
    .pop-header-left
      display flex
      p
        font-size 14px
        color #8D9091
        line-height 20px
      p:nth-of-type(1)
        padding-bottom 4px
        span
          font-size 16px
          font-weight bold
          line-height 22px
          color #2D323B
          margin-right 6px
      .pop-avatar
        width 42px
        height 42px
        border-radius 50%
        margin-right 20px
      .userinfo-email
        color #8c94a0
    .pop-header-right
      .invite
        margin-right 8px
      >button
        border-radius 14px
        background #F4F7F8
        border none
        color #2D323B
        font-size 14px
        line-height 20px
        padding 4px 17px
        cursor pointer
        outline none
  .pop-order
    padding 27px 23px 30px 40px
    .order-icon
      width 22px
      height 22px
      margin-right 8px
    .pop-calc
      display flex
      justify-content space-between
      align-items center
      .pop-calc-left
        display flex
        align-items center
        font-size 14px
        color #6E6E6E
        .num-lan
          font-size 16px
          color #39a1f4
      .pop-calc-right
        >button
          border none
          border-radius 14px
          color #2D323B
          font-size 14px
          line-height 20px
          padding 4px 17px
          background #F4F7F8
          cursor pointer
          outline none
    .pop-storage
      display flex
      align-items center
      padding-top 10px
      p>span
        font-size 14px
        color #909399
        margin-right 9px
      >p
        .num-lan
          font-size 16px
          color #39a1f4
  .pop-nav
    padding 30px 40px
    display flex
    font-size 14px
    line-height 20px
    color #6E6E6E
    justify-content space-around
    .pop-nav-item
      cursor pointer
  .pop-footer
    background #F4F7F8
    padding 16px 12px
    font-size 14px
    line-height 20px
    display flex
    justify-content center
    >span
      cursor pointer
  .line
    height 2px
    width 100%
    background #F4F4F4
</style>
